<?php

function getRand($num = 5){
    $string = '';
    for($i = 0; $i < $num; $i++){
        $string .= chr(mt_rand(97,122));
    }
    return $string;
}

function getDates($type = 1,$time = 0){
    $datetime = '';
    switch($type){
        case 1:
            $datetime = date('Y-m-d H:i:s');
            break;
        case 2:
            $datetime = time();
            break;
        case 3:
            $datetime = date('Y-m-d H:i:s',$time);
            break;
    }
    return $datetime;
}
function uploadFile($fileDATA,$filePath = 'Upload/head/'){
    if(empty($fileDATA)){
        return ['status' => 1, 'msg' => '没有上传图片！'];
    }
    $typeArr = ['image/jpeg','image/png','image/jpg','image/gif'];
    if(!in_array($fileDATA['type'],$typeArr)){
        return ['status' => 1, 'msg' => '头像不符合要求！'];
    }
    if($fileDATA['size'] > 204800){
        return ['status' => 1, 'msg' => '头像超过了允许的大小！'];
    }
    $fileName = time().rand(0,9999).'.'.end(explode('.',$fileDATA['name']));
    if(!is_dir($filePath) && !is_writable($filePath)){
        return ['status' => 1, 'msg' => '文件夹存储异常！'];
    }
    $litPath = $filePath.$fileName;
    if(!move_uploaded_file($fileDATA['tmp_name'],$litPath)){
        return ['status' => 1, 'msg' => '头像上传失败！'];
    }
    return $litPath;
}

function make_tree($list,$pk='id',$pid='pid',$child='_child',$root=0){//查询出来的数组作为list传进来，里面有ID，pid，因为$pk='id' 所以直接把id的值给了$pk
    $tree = array();
    $packData = array();
    foreach($list as $data){//查询结果为二维数组，所以要先遍历一下，把里面的东西便利出来
        $packData[$data[$pk]] = $data;//$packdata本身就是一个数组，把便利出来的data里面的pk也就是id作为键给了packdata，重新把data再次付给了packdata，内容没变，把二维数组的键换为了data的id
    }
    foreach($packData as $key => $val){
        if($val[$pid] == $root){//root为0，如果pid为0，就是顶级栏目
            $tree[] = & $packData[$key];//顶级栏目，直接把pid为0的这次循环的值用&给新数组，tree本身就是一个数组，再次给他值，他就成了二维数组
        }else{
            $packData[$val[$pid]][$child][] = & $packData[$key];//pid不为0，把值给它上面键为pid的packdata注意这里不是tree，packdata和tree的值相关联他俩共用一个内存，tree用的是packdata的值，在pid为0的二维数组里面加一个数组，tree也会随之加
        }
    }
    return $tree;
}

function getTree($data,$pid = 0,$level = 0,$html = '&nbsp;'){
    $arr = [];
    foreach($data as $v){
        if($v['pid'] == $pid){
            $v['level'] = $level + 1;
            $v['html'] = str_repeat($html,$level);
            $arr[] = $v;
            $arr = array_merge($arr,getTree($data,$v['id'],$level +1,$html));
        }
    }
    return $arr;
}